# Create your views here.
import datetime,time,cgi,urlparse
from urllib2 import Request, urlopen

from opent.auth import SinaOAuthHandler
#NetEaseOAuthHandler,QQOAuthHandler,SohuOAuthHandler,DoubanOAuthHandler
from models import Profile

from django.http import HttpResponse,Http404
from django.shortcuts import redirect,render_to_response
from django.contrib.auth import authenticate , login as auth_login, logout as auth_logout
from django.contrib.auth.models import User
from django.contrib.auth.decorators import login_required
from django.template import Context, RequestContext, loader

# 
# def getOpenT(site):
callback = 'http://127.0.0.1:8000/users/authenticate/'
# 	#sina oauth 
# 	sinaopent = SinaOAuthHandler("1252752896","404cfc018d9e79d313b62cb818248df8",callback)
# 	#qq oauth
# 	#qqopent = QQOAuthHandler("f1cffc96c1e144aaa8bf277d45f83f6f","0adbb59a2858dfe9ff2593617b2614b2",'http://127.0.0.1:8000/',True)
# 	#163 oauth
# 	neopent = NetEaseOAuthHandler('I4SrBAAKnM3fnYul','EUxSv4kOXSChVlOUQ5tsOlUtl4qlynjY',callback)
# 	#sohu oauth
# 	sohuopent = SohuOAuthHandler('Aczvum4m5IEsphW4nNNO','zCOO3nIGsHlpMOk7^v7B#FAL=Pb1#9eYKU-B5C(7',callback)
# 	#douban oauth
# 	#opent = DoubanOAuthHandler('c89c1ea3d05d8d21','c4579586f41a90372f762cb65c78be5d','http://127.0.0.1:8000/')
# 	opents = {
# 		'sina':sinaopent,
# 		'163':neopent,
# 		'sohu':sohuopent,
# 		}
# 	return opents[site]

opent = SinaOAuthHandler("1252752896","404cfc018d9e79d313b62cb818248df8",callback)
	
def login(request):
	return render_to_response('users/login.html',{})

@login_required
def logout(request):
    auth_logout(request)
    return redirect('/')
	
def signin(request,site):
	if site == '163' :
		aurl = opent.get_authorization_url(True)
	else :
		aurl = opent.get_authorization_url()
	request.session['site'] = site
	request.session['request_token'] = opent.request_token
	return redirect(aurl)
	
def authenticated(request):
	site = request.session['site']
	request_token = request.session.get('request_token')
	oauth_verifier = request.GET.get('oauth_verifier', None)
	
	opent.set_request_token(request_token.key,request_token.secret)
	access_token = opent.get_access_token(oauth_verifier)
	user_id = opent.get_username()
	
	try:
		user = User.objects.get(username=user_id)
	except User.DoesNotExist:
		user = User.objects.create_user(user_id,'%s@%s' % (user_id,site) , access_token.secret)
		profile = Profile()
		profile.user = user
		profile.oauth_token = access_token.key
		profile.oauth_secret = access_token.secret
		profile.save()
	
	user = authenticate(username=user_id,password=access_token.secret)
	auth_login(request, user)
	
	return redirect('/')
	
def index(request):
	return render_to_response('index.html',{'asks':(1,2,3,4,5)},RequestContext(request))